package com.example.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.mapper.UserMapper;
import com.example.demo.entity.Message;
import com.example.demo.entity.User;
import com.example.demo.util.IPUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Controller
public class EmailLoginController {
    @Autowired
    private UserMapper um;

    @RequestMapping("/emailLogin")
    public void regist(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        String email = request.getParameter("email");
        String inputcode = request.getParameter("code");
        String code = (String) request.getSession().getAttribute("emailCode");
        User u = um.selectByName(username);
        if (u != null&&u.getEmail().equals(email)) {
            if (code.equals(inputcode)) {
                request.getSession().setAttribute("user",u);
                um.updateUserIPAndTime(IPUtil.getClientIpAddress(request), u.getId());
                response.getWriter().write(JSONObject.toJSONString(Message.success("Success login")));
            } else response.getWriter().write(JSONObject.toJSONString(Message.failure(400, "code is error")));
        }else response.getWriter().write(JSONObject.toJSONString(Message.failure(400, "Error")));
    }
}
